var ELE = {};
var columns = 0;
var maxrow = 0;
function zs_init(){
    
	
    
//    var v = jQuery.prototype.jquery;
//    if(v!='1.10.2'){
//    	var jQueryjq = jQuery.noConflict(true);
//    }
//	
    
   
	var nodeType;
    var requestId = window.parent.document.getElementById("reqid").getAttribute("value");
    var domainName = window.parent.document.getElementById("dname").getAttribute("value");
    if (domainName.indexOf('http') < 0) {
        domainName = 'http://' + domainName;
    }

    
    getTemplateDetail(domainName, requestId);//获取模板details回显

    //防止右键时出现浏览器菜单
    var listText = {
    	    text: "列表文本",
    	    func: function() {
    	     
	         var id = ELE.id;
	         var unique_id = ELE.unique_id;
	         //jQuery("#head th", window.parent.document).length;
	         
	        
             var e = jQuery.smartMenu.getE();
	         var ft = jQuery(e.target).first();
	    	 var xp = jQuery(ft).ellocate();
             addTemplateDetail(domainName, requestId, 'list', id,'text',xp.css);
	         
    	    }    
    	}, listHref = {
    	    text: "列表链接",
    	    func: function() {
    	    	 var id = ELE.id;
    	        
	    	    	
                 var e = jQuery.smartMenu.getE();
 	        	 var ft = jQuery(e.target).first();
 	    	     var xp = jQuery(ft).ellocate();
	             addTemplateDetail(domainName, requestId, 'list', id,'href',xp.css);
    	        
    	    }    
    	}, eleText = {
    	    text: "单元素文本",
    	    func: function() {
    	    	
    	    	 var id = ELE.id;
    	       
	    	    	
                    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
                    addTemplateDetail(domainName, requestId, 'element', id,'text',xp.css);
               
    	    }
    	}, eleHref = {
    	    text: "单元素链接",
    	    func: function() {
    	    	 var id = ELE.id;
    	        
	    	    	
                    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
                    addTemplateDetail(domainName, requestId, 'element', id,'href',xp.css);
               
    	    }    
    	}, doMy = {
    	    text: "自定义",
    	    func: function() {
    	    	    var id = ELE.id;
    	    	    columns = parseInt(columns);
    	    	    columns =  columns + 1;
    	             var columnName = '属性' + columns;
                    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
    	    	    window.parent.showDoMySel(id, columnName);
    	    	    
                    
                    //addTemplateDetail(domainName, requestId, columnName, 'element', id,'img',1);
               
    	    }    
    	}, onPage = {
    	    text: "点击翻页",
    	    func: function() {
    	    	    var id = ELE.id;
    	    	    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
    	    	    getElePath(domainName, requestId,id,'click');
                    
                    //addTemplateDetail(domainName, requestId, columnName, 'element', id,'img',1);
               
    	    }    
    	}, onAjaxPage = {
    	    text: "AJAX翻页",
    	    func: function() {
    	    	    var id = ELE.id;
    	    	    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
    	    	    getElePath(domainName, requestId,id,'ajax');
    	    	    //window.parent.showSetting(xp.css,'ajax');
    	    	    //getElePath(domainName, requestId,id,'ajax');
                    
                    //addTemplateDetail(domainName, requestId, columnName, 'element', id,'img',1);
               
    	    }    
    	}, onPrePage = {
    	    text: "翻页前置条件",
    	    func: function() {
    	    	    var id = ELE.id;
    	    	    var e = jQuery.smartMenu.getE();
    	        	var ft = jQuery(e.target).first();
    	    	    var xp = jQuery(ft).ellocate();
    	    	    getPreElePath(domainName, requestId,id);
    	    	    // window.parent.showPreSetting(xp.css);
    	    	    //getElePath(domainName, requestId,id,'ajax');
                    
                    //addTemplateDetail(domainName, requestId, columnName, 'element', id,'img',1);
               
    	    }    
    	}
    	var mailMenuData = [
    	    [listText, listHref,eleText,eleHref,doMy,onPage,onAjaxPage,onPrePage]
    	];
    jQuery("body").smartMenu(mailMenuData, {
        name: "all",
        //根据已读与否状态显示不同的上下文菜单
        beforeShow: function() {
            //右键选中当前行  
        	var v = jQuery.prototype.jquery;
            if(v!='1.10.2'){
            	var jQueryjq = jQuery.noConflict(true);
            }
        	if(jQuery.smartMenu){
        		 jQuery.smartMenu.remove();
        	}
            
            //动态数据，及时清除
           
            ELE = {};
        	
            //确定显示数据 - 主要是已读与未读
           
        },afterShow: function() {
        	

        	var e = jQuery.smartMenu.getE();
        	var ft = jQuery(e.target).first();
            var id = ft.attr("__thinkdata_id") || '';
            var unique_id = ft.attr("unique_id") || '';
            ELE.id= id;
            ELE.unique_id=unique_id;
        }
    
    
    });
    
  
    jQuery("body").mouseover(function (e) {
        var ft = jQuery(e.target).first();
        var id = ft.attr("__thinkdata_id") || '';
        if (id != '') {
            ft.addClass("__thinkdata_hover");
           //var xp =  getXpath(e,this);
           //console.log(xp)
           //var path = readXPath(ft.context);
//           layer.tips('路径:'+path, "[__thinkdata_id=" + id + "]", {
//        	   tips: [1, '#3595CC'],
//        	   time: 4000
//        	 });
        	 

       
        }
    }).mouseout(function (e) {
        var ft = jQuery(e.target).first();
        var id = ft.attr("__thinkdata_id") || '';
        if (id != '') {
            ft.removeClass("__thinkdata_hover");
        }
    });



}
jQuery(document).ready(function(){
	columns = window.parent.document.getElementById("columns").getAttribute("value");
	zs_init();
   
});

function addTemplateDetail(domainName, requestId, type, id,attr,css) {
	
     
     columns = parseInt(columns);
     columns =  columns + 1;
     var columnName = '属性' + columns;
     
    jQuery.post(domainName + "/action/tmpl/t/addTemplateDetail", {
        "requestId": requestId,
        "columnName": columnName,
        "type": type,
        "attr": attr,
        "thinkDataId": id,
        "orderby": columns
        //"csspath": css
    }, function (data) {
        console.log(data)
        if (data.code == 200) {
        	var eles = data.data;
        	if(eles!=null&&eles!=undefined){
        		for (var i = 0; i < eles.length; i++) {
        	        addData(eles[i], type,false); 
        	    }
        	} 
        }
    });

}

function delTemplateDetail(domainName, unique_id) {
    jQuery.ajax({
        type: "POST",
        url: domainName + "/action/tmpl/t/delTemplateDetail",
        async: false,
        data: {uniqueId: unique_id},
        dataType: "json",
        success: function (data) {
            if (data.code==200) {
                delData(unique_id);//删除高亮和list
            } else {
                console.log(data.msg);
            }
        },
        error: function () {
            console.log('err');
        }
    });
}



function delData(unique_id) {
    jQuery("[unique_id=" + unique_id + "]").removeClass('__thinkdata_highlight');//移除左键高亮
    jQuery("[unique_id=" + unique_id + "]").removeClass('__thinkdata_highlight2');//移除右键高亮
    var eles = jQuery("[unique_id=" + unique_id + "]");
    for (var i = 0; i < eles.size(); i++) {
        eles[i].removeAttribute("unique_id");
    }

    if (jQuery("#head", parent.document).children().length == 2) {
        var obj0 = new Object();
        var obj1 = new Object();
        jQuery('#head', parent.document).children().each(function (index, element) {
            //console.log(index + ';' + jQuery(element));
            if (index == 0) {
                obj0 = element;
            }
            if (index == 1) {
                obj1 = element;
            }
        });
        if (obj0.attributes[1].nodeValue.indexOf(obj1.attributes[1].nodeValue) || obj1.attributes[1].nodeValue.indexOf(obj0.attributes[1].nodeValue)) {
            //剩下的两列如果是一对，那么将多余tr标签删除
            jQuery('#cols', parent.document).html('');
        }
    } else if (jQuery("#head", parent.document).children().length == 1) {//删除最后一列的同时清空tbody，否则出现空行
        jQuery('#cols', parent.document).html('');
    }

    jQuery("[uuid=" + unique_id + "]", parent.document).remove();//清除td
  
    deleteEmptyRow();//删除多余空行
    window.parent.map.remove(unique_id);//在map对象中移除
}


function addData(row, mouseIndex,callBack) {//callBack:true表示是回显
    var unique_id = row.unique_id;
    var th = row.th;
  
    /**
    if(row.tag_name=='a'||row.tag_name=='A'){
        th = "<th  uuid='" + unique_id + "' index="+index+">" + row.column_name + " <i class='fa fa-trash-o' style='cursor:pointer' onclick=\"delCol(this,'" + unique_id + "')\"></i> </th><th index="+index+"  uuid='" + unique_id + "_a'>" + row.column_name + "链接 <i class='fa fa-trash-o' style='cursor:pointer'  onclick=\"delCol(this,'" + unique_id + "_a')\"></i></th>"
    } else if (row.elements[0].src != '') {
        th = "<th  index="+index+" uuid='" + unique_id + "'>" + row.column_name + "链接  <i class='fa fa-trash-o' style='cursor:pointer'  onclick=\"delCol(this,'" + unique_id + "')\"></i> </th>"
    } else {
        th = "<th index="+index+"  uuid='" + unique_id + "'>" + row.column_name + " <i class='fa fa-trash-o' style='cursor:pointer'  onclick=\"delCol(this,'" + unique_id + "')\"></i> </th>"
    }
	**/
    var rlength =  jQuery("#rows", window.parent.document).val();
    rlength =  parseInt(rlength);

    jQuery("#head", window.parent.document).append(th);
    var thLength = jQuery("#head th", window.parent.document).length;
    var trLength = jQuery("#cols tr", window.parent.document).length;
    var rowLength = row.elements.length;
    if (rowLength > 0) {
        var eles = row.elements;
        var rows = eles.length;
        if (rowLength > trLength) {
            var last = rowLength - trLength;
            var x = 0;
            if(trLength>0){
            	x = trLength;
            }
            for (var i = 0; i < last; i++) {
                jQuery("#cols", window.parent.document).append("<tr id='r"+(x+i)+"'></tr>");
            }
            rows = rowLength;
        } else if (trLength > rowLength) {
            rows = trLength;
        }
        
        if(callBack){
        	rows=rlength;
        }
      
        if (mouseIndex == 'list') {
            for (var i = 0; i < rows; i++) {
                var ele = eles[i];
                var td ;
                if (ele == null || ele == undefined || ele == '') {
                	
                	td="<td uuid='" + unique_id + "'></td>"
                }else{
                	td = ele.td;
                }
               
                var tr = jQuery("#cols", window.parent.document).find("tr").eq(i);
                var tdLength = jQuery(tr).find("td").length;
                var j = 1;
                if (ele != null && ele != undefined && ele != '') {
                

                    jQuery("[__thinkdata_id=" + eles[i].id + "]").addClass("__thinkdata_highlight");//添加左键高亮

                    jQuery("[__thinkdata_id=" + eles[i].id + "]").attr("unique_id", unique_id);

                }
              
                var colsLength = tdLength + j;
                if (thLength > colsLength) {
                	var thtd = jQuery("#head th", window.parent.document);
                	var max = (thLength - colsLength); 
                    for (var k = 0; k < max; k++) {
                    	var thi = (max-(k+1)) ;
                    	if(thi<0){
                    		thi = 0;
                    	}
                    	var thitem = thtd[thi];
                    	var thid = jQuery(thitem).attr("uuid");
                    	td = "<td  uuid='" + thid + "'></td>" + td;
                    }
                }
                
                
                jQuery(tr, window.parent.document).append(td);
               
                var hdIndex = jQuery("#head th[index=1]", window.parent.document);
                var array= new Array();
                for(var m=0;m<hdIndex.length;m++){
                
                	array.push(hdIndex[m].cellIndex);
                }
                
                
                var trs = jQuery("#cols", window.parent.document).find("tr").eq(0);
                var tds = jQuery(trs).find("td");
            	for(var j=0;j<tds.length;j++){
            		var tdj = tds[j];
            		var v = jQuery(tdj).text();
            		var is = jQuery.inArray(j, array);
            		if(is>=0){
            			for(var r=0;r<=rows;r++){
            				var ttd = jQuery("#cols", window.parent.document).find("tr").eq(r).find("td");
            				jQuery(ttd[j]).text(v);
            				// td = "<td  uuid='" + unique_id + "'></td>"
            			}
            		}
            	}
            	
  
            }
        } else {
            var ele = eles[0];
            var td = "";
           
            var tdd = ele.td;
            for(var l=0;l<rows;l++){
                 var tr = jQuery("#r"+l, window.parent.document);
//                 //var clength = tr.cells.length;
//                 console.log(tdd);
                 jQuery(tr, window.parent.document).append(tdd);
            }
           
            jQuery("[__thinkdata_id=" + eles[0].id + "]").addClass("__thinkdata_highlight2");//添加右键高亮
            jQuery("[__thinkdata_id=" + eles[0].id + "]").attr("unique_id", unique_id);
        }
    
      
        window.parent.addMap(unique_id, row);
       
       
        
    }
}

function getElePath(domainName, requestId,id,ele) {
    jQuery.post(domainName + "/action/tmpl/t/getElePath", {
        "requestId": requestId,
        "id":id
    }, function (data) {
        if (data.code == 200) {
        	 window.parent.showSetting(data.data,ele);
        }else{
        	layer.msg(data.msg)
        }
    });
}

function getPreElePath(domainName, requestId,id) {
    jQuery.post(domainName + "/action/tmpl/t/getElePath", {
        "requestId": requestId,
        "id":id
    }, function (data) {
        if (data.code == 200) {
        	 window.parent.showPreSetting(data.data);
        }else{
        	layer.msg(data.msg)
        }
    });
}



function getTemplateDetail(domainName, requestId) {
    jQuery.post(domainName + "/action/tmpl/t/getTemplateDetail", {
        "requestId": requestId
    }, function (data) {
        if (data.code == 200) {
            renderTemplate(data.data);
        }
    });
}

function renderTemplate(eles) {
	if(eles!=null&&eles!=undefined){
		for (var i = 0; i < eles.length; i++) {
	      
	        addData(eles[i], eles[i].column_type,true);
	        
	    }
	}
    
}

function parseElePath(domainName, list_path, node_path, unique_id, request_id, column_name, column_type,attr) {

	 columns = parseInt(columns);
    
    //var index =  (trIndex + 1);
	window.parent.delCol(unique_id);
    jQuery.post(domainName + "/action/tmpl/t/parseElePath", {
        "listPath": list_path,
        "nodePath": node_path,
        "requestId": request_id,
        "columnName": column_name,
        "columnType": column_type,
        "attr": attr,
        "orderby":columns
    }, function (data) {
        if (data.code == 200) {
            if (data.data.elements.length > 0) {
                addData(data.data,  column_type, false);
            }
        }
    });
}

function deleteEmptyRow() {
    var isEmpty = true;
    jQuery("#cols tr", parent.document).each(function (index, item) {
        jQuery(item).find("td").each(function (tdindex, tditem) {
            if (jQuery(tditem).text()) {
                isEmpty = false;
            }
        });
        if (isEmpty) {
            jQuery(item).remove();
        }
        isEmpty = true;
    });
}
function getXpath(e,o){
	e.stopPropagation();
	
	var  xpath = o.tagName;
    while (o = o.parentNode) { xpath = o.tagName + '/' + xpath; if (o.tagName == 'BODY') break; }
    return '/' + xpath;
}

   


function readXPath(element) {
    if (element.id !== "" && typeof(element.id) != 'undefined') {//判断id属性，如果这个元素有id，则显 示//*[@id="xPath"]  形式内容
        return '//*[@id=\"' + element.id + '\"]';
    }
    //这里需要需要主要字符串转译问题，可参考js 动态生成html时字符串和变量转译（注意引号的作用）
    if (element == document.body) {//递归到body处，结束递归
        return '/html/' + element.tagName.toLowerCase();
    }
    var ix = 1,//在nodelist中的位置，且每次点击初始化
        siblings = element.parentNode.childNodes;//同级的子元素

    for (var i = 0, l = siblings.length; i < l; i++) {
        var sibling = siblings[i];
        //如果这个元素是siblings数组中的元素，则执行递归操作
        if (sibling == element) {
            return arguments.callee(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix) + ']';
            //如果不符合，判断是否是element元素，并且是否是相同元素，如果是相同的就开始累加
        } else if (sibling.nodeType == 1 && sibling.tagName == element.tagName) {
            ix++;
        }
    }
};
